package com.svt;

import java.io.File;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

public class VideoUtils {
	
	public static void catVideo(File[] fs,String destDir,String newName){
		String filename = newName; 
		String p = destDir.replaceAll("\\\\", "/");
		if(!p.endsWith("/")){
			p += "/";
		}
		File f =  new File(p+"new/");
		f.mkdirs();
		StringBuffer fsstr = new StringBuffer();
		StringBuffer instr = new StringBuffer();
		StringBuffer scalestr = new StringBuffer();
		int max = 0;
		int maxidx = -1;
		String maxrstr = null;
		for (int i=0;i<fs.length;i++) {
			File file = fs[i];
			if(file==null)
				continue;
			String infoc = "ffmpeg -i \""+file.getAbsolutePath()+"\"";
			Map m = ShellUtil.executeShell(infoc);
			String rt = (String)m.get("msg");
			String vinfo = StringUtils.substringBetween(rt, "Stream #0:0", "\n");
			final Pattern pt =  Pattern.compile("\\s(\\d+x\\d+)[,|\\s]");
			Matcher mc = pt.matcher(vinfo);
			String r = null;
			if(mc.find()){
				r = mc.group(1).replace("x", ":");
			}
			String[] rs = r.split(":");
			int rw = Integer.parseInt(rs[0]);
			if(rw>max){
				max = rw;
				maxidx = i;
				maxrstr = r;
			}
		}
		
		int n=0;
		for (int i=0;i<fs.length;i++) {
			File file = fs[i];
			if(file==null)
				continue;
			fsstr.append(" -i \"").append(file.getAbsolutePath()).append("\" ");
			instr.append("["+n+"v] ["+n+":1] ");
			String sstr = null;
			if(i==maxidx){
				sstr = "["+n+":v]setsar=1["+n+"v];";
			}else{
				sstr = "["+n+":v]scale="+maxrstr+":force_original_aspect_ratio=decrease,setsar=1,pad="+maxrstr+":(ow-iw)/2:(oh-ih)/2["+n+"v];";
			}
			scalestr.append(sstr);
			n++;
		}
		
		String catc = "ffmpeg -y "+fsstr+"-filter_complex \""+scalestr+instr+"concat=n="+n+":v=1:a=1 [v1] [a1]\" -map [v1] -map [a1] \""+p+"new/"+filename+"\"";
		Map m = ShellUtil.executeShell(catc);
		System.out.println(catc);
		System.out.println(m.get("msg"));
	}

}
